package com.mlizhi.modules.spec.setting;

import java.util.HashMap;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.ViewGroup.LayoutParams;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.mlizhi.base.NetWorkManager;
import com.mlizhi.base.SecurityUtil;
import com.mlizhi.base.Session;
import com.mlizhi.kingdom.R;
import com.mlizhi.modules.spec.util.JsonUtil;
import com.mlizhi.utils.Constants;
import com.umeng.analytics.AnalyticsConfig;
import com.umeng.analytics.MobclickAgent;

/**
 * User: special
 * Date: 13-12-22
 * Time: 下午3:28
 * Mail: specialcyci@gmail.com
 */
public class SpecSettingMineUserSexActivity extends Activity {

    private Session mSession;
    private Context mContext;
    private String userSex;
    private RadioGroup userSexGroup;
    
    
    @SuppressLint("SetJavaScriptEnabled")
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        mSession = Session.get(getApplicationContext());
        setContentView(R.layout.activity_spec_setting_mine_sex);
        /** 发送策略定义了用户由统计分析SDK产生的数据发送回友盟服务器的频率。 */
        MobclickAgent.updateOnlineConfig( mContext );
        /** 设置是否对日志信息进行加密, 默认false(不加密). */
        AnalyticsConfig.enableEncrypt(true);
        getWindow().setLayout(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);       
        getWindow().setGravity(Gravity.CENTER);
        userSexGroup = (RadioGroup) findViewById(R.id.user_setting_sex_group);
        if(Constants.USER_SEX_FEMALE.equals(mSession.getUserSex())){
        	userSexGroup.check(R.id.user_setting_sex_female);
        }else if(Constants.USER_SEX_MALE.equals(mSession.getUserSex())){
        	userSexGroup.check(R.id.user_setting_sex_male);
        }
        userSexGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch (checkedId) {
				case R.id.user_setting_sex_female:
//				mSession.setUserSex(userSex);
					userSex = Constants.USER_SEX_FEMALE;
					break;
				case R.id.user_setting_sex_male:
					userSex = Constants.USER_SEX_MALE;
					break;
				default:
					break;
				}
				updateUserSex();
			}
		});
        
    }

    
    /**
     * 修改头像
     * @param view
     */
    private RequestQueue mRequestQueue;
    public void updateUserSex() {
        boolean netUsable = NetWorkManager.getNewInstance().isNetworkConnected(mContext);
        if (netUsable) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
            // Request a string response from the provided URL.
            StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.URL_POST_UPDATE_INFO,
            		listener , new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(mContext,error.getMessage(),Toast.LENGTH_SHORT).show();
                    setResult(RESULT_CANCELED);
                }
            }){
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    String timestamp = SecurityUtil.getTimestamp();
                    Map<String, String>  params = new HashMap<String, String>();
                    params.put("id", mSession.getUid());
                    params.put("sex", userSex);
                    params.put(Constants.URL_TIMESTAMP,timestamp );
                    params.put(Constants.URL_KEY,SecurityUtil.getMd5String(timestamp));
                    return params;
                }
            };
            mRequestQueue.add(stringRequest);
            mRequestQueue.start();
        }else {
            Toast.makeText(mContext,R.string.net_connected_failure,Toast.LENGTH_SHORT).show();
        }
    }
    
    
    Response.Listener<String> listener = new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            String code = JsonUtil.getHeaderCode(response);
            if(Constants.RESULT_JSON_HEADER_CODE_SUCCESS.equals(code)){
            	setResult(RESULT_OK);
            	mSession.setUserSex(userSex);
                Toast.makeText(mContext, "性别修改成功！", Toast.LENGTH_SHORT).show();
                finish();
            }else {
            	Toast.makeText(mContext, "提交失败！", Toast.LENGTH_SHORT).show();
//                Toast.makeText(mContext, JsonUtil.getHeaderErrorInfo(response), Toast.LENGTH_SHORT).show();
                setResult(RESULT_CANCELED);
            }
        }
    };
    
    @Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart("SplashScreen"); //统计页面(仅有Activity的应用中SDK自动调用，不需要单独写)
	    MobclickAgent.onResume(this);          //统计时长
	}

	@Override
	public void onPause() {
		super.onPause();
		 MobclickAgent.onPageEnd("SplashScreen"); // （仅有Activity的应用中SDK自动调用，不需要单独写）保证 onPageEnd 在onPause 之前调用,因为 onPause 中会保存信息 
		    MobclickAgent.onPause(this);
	}
}
